package express

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	error2 "OnlineRetailers/models/errorDeal"
	"OnlineRetailers/models/express"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"net/http"
)

type Get struct {
	beego.Controller
}

func (c *Get) Get() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/express/Get"
	log := &error2.Log{}
	ShipperCode := c.GetString("ShipperCode")
	LogisticCode := c.GetString("LogisticCode")
	CustomerMark := c.GetString("CustomerMark")
	session, err := getSession()
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	express1, err := getData(ShipperCode, LogisticCode, CustomerMark, session)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	c.Data["json"] = express1
	return
}

//func Get1()  {
//	session,_:=getSession()
//	getData("JD","JD0064507452657","1511",session)
//}
func getData(ShipperCode, LogisticCode, CustomerMark, session string) (*express.Express, error) {

	url := models.GetDataUrl

	express := new(express.Express)
	//fmt.Println(url)
	bodys := bytes.NewBuffer([]byte(`{"FunClassName":"KdniaoWebsite.Services.KdnInterface.KdnServices","FunMethodName":"GetTracks","ParamClassName":"KdniaoWebsite.Model.KdnInterface.SearchRouteParam","ParamType":"Entity","ParamData":"{\"ShipperCode\":\"` + ShipperCode + `\",\"LogisticCode\":\"` + LogisticCode + `\",\"CustomerMark\":\"` + CustomerMark + `\"}"}`))
	req, err := http.NewRequest("POST", url, bodys)

	req.Header.Set("Host", models.GetSessionHost)
	//Host: jwxt.hebic.cn
	req.Header.Set("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0")
	//User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0
	req.Header.Set("Referer", models.GetSessionUrl+"v4/Memberships.aspx")
	//Accept: application/json, text/javascript, */*; q=0.01
	req.Header.Set("Origin", models.GetSessionWeb)
	//Origin: http://jwxt.hebic.cn
	//Connection: keep-alive
	req.Header.Set("Cookie", "ASP.NET_SessionId="+session)
	//Cookie: ASP.NET_SessionId=jzqwb5viciurunsnws0f0cqo
	req.Header.Set("Connection", "keep-alive")
	//Referer: http://jwxt.hebic.cn/xsxk/zzxkyzb_cxZzxkYzbIndex.html?gnmkdm=N253512&layout=default&su=191305080930
	//Cookie: JSESSIONID=E57F810953C5B3DE049C2C47A9F294BF; SF_cookie_9=26458859
	client := &http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	fmt.Println(string(body))

	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	err = json.Unmarshal(body, express)

	if err != nil {
		return nil, err
	}
	//fmt.Println(express)
	return express, err
}
